package com.otod.pm.prj.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.otod.base.exception.AppException;
import com.otod.base.json.JsonSuccess;
import com.otod.commons.auth.SessionUserHolder;
import com.otod.commons.auth.SessionUserUtil;
import com.otod.commons.utils.Collections3;
import com.otod.commons.utils.DateUtils;
import com.otod.commons.utils.StringUtils;
import com.otod.commons.web.BaseController;
import com.otod.pm.comment.service.SubmitInfoService;
import com.otod.pm.comment.vo.AsmgSubmitInfoVo;
import com.otod.pm.constants.PmConstant;
import com.otod.pm.prj.bo.PrjFruitFileBo;
import com.otod.pm.prj.bo.TaskCalendarBo;
import com.otod.pm.prj.bo.TaskFileBo;
import com.otod.pm.prj.service.PmTaskEmpService;
import com.otod.pm.prj.service.ProjectService;
import com.otod.pm.prj.service.StepService;
import com.otod.pm.prj.service.TaskService;
import com.otod.pm.prj.service.TeamService;
import com.otod.pm.prj.vo.PmTaskEmpVo;
import com.otod.pm.prj.vo.ProjectVo;
import com.otod.pm.prj.vo.StepVo;
import com.otod.pm.prj.vo.TaskVo;
import com.otod.pm.prj.vo.TeamVo;
import com.otod.sys.amcm.MessageConstant;
import com.otod.sys.amcm.service.AmcmMsgAppService;
import com.otod.sys.code.service.ICodeService;
import com.otod.sys.emp.service.IEmpService;
import com.otod.sys.file.service.IFileService;
import com.otod.sys.vo.AuapTEmpVo;
import com.otod.sys.vo.FileVo;


/**
 * 任务管理
 * @author jqiu
 */
@Controller
@RequestMapping("pm/task")
public class TaskController extends BaseController {

	@Autowired
	private TaskService taskService;
	
	@Autowired
	private ICodeService codeService;
	
	@Autowired
	private AmcmMsgAppService msgService;
	
	@Autowired
	private SubmitInfoService submitService;
	
	 @Autowired
	IEmpService empService;
	 
	 @Autowired
	TeamService teamService;
	
	 @Autowired
	 IFileService fileService;
	 
	 @Autowired
	 private ProjectService projectService;
	 
	 @Autowired
	 private StepService stepService;
	 
	 @Autowired
	 private SubmitInfoService submitInfoService;
	 
	 @Autowired
	private PmTaskEmpService taskEmpService;

	/**
	 * 新增任务
	 * @param taskVo
	 * @return
	 */
	@RequestMapping(value ="insert", method = RequestMethod.POST)
	@ResponseBody
	public TaskVo insert(TaskVo taskVo,HttpServletRequest request) {
		super.setInsertOperInfo(taskVo);
		return taskService.insert(taskVo);
	}

	/**
	 * 修改任务
	 * @param taskVo
	 * @return
	 * @throws AppException 
	 */
	@RequestMapping(value ="update", method = RequestMethod.POST)
	@ResponseBody
	public TaskVo update(TaskVo vo,HttpServletRequest request) throws AppException {
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("uuid", vo.getUuid());
		map.put("taskName", vo.getTaskName());
		map.put("prjId", vo.getPrjId());
		map.put("startDate", vo.getStartDate());
		String prjStatus = projectService.getById(vo.getPrjId()).getStatus();
		if(StringUtils.isEmpty(vo.getEmpNo())){
			map.put("status",PmConstant.TASK_STATUS_READY);
			vo.setStatus(PmConstant.TASK_STATUS_READY);
		}else{
			
			if (null == vo.getStartDate()) {
				throw new AppException("项目开始时间不能为空");
			}
			
			if(vo.getStartDate().getTime()>DateUtils.getCurrentDate().getTime()){
				
				map.put("status",PmConstant.TASK_STATUS_READY);
				vo.setStatus(PmConstant.TASK_STATUS_READY);
			}else if(PmConstant.PRJ_STATUS_STARTING.equals(prjStatus)){
				map.put("status",PmConstant.TASK_STATUS_STARTING);
				vo.setStatus(PmConstant.TASK_STATUS_STARTING);
			}else{
				map.put("status",PmConstant.TASK_STATUS_READY);
				vo.setStatus(PmConstant.TASK_STATUS_READY);
			}
		}
		map.put("planEndDate", vo.getEndDate());
		map.put("empNo", vo.getEmpNo());
		map.put("taskType", vo.getTaskType());
		map.put("depict", vo.getDepict());
		map.put("empNos", vo.getEmpNos());//协作人员信息
		super.setUpdateOperInfo(map);
		taskService.update(map);
		
		vo.setEndDateFormat(DateUtils.formatDate(vo.getEndDate(),"yyyy-MM-dd"));
		vo.setStartDateFormat(DateUtils.formatDate(vo.getStartDate(),"yyyy-MM-dd"));
		if(!StringUtils.isEmpty(vo.getEmpNo())){
			AuapTEmpVo empVo = empService.findByEmpNo(vo.getEmpNo());
			if(empVo != null){
				vo.setEmpName(empVo.getEmpName());
				
					msgService.installMsgVo(vo, MessageConstant.TASK_UPDATE);// update Vo
				
			}
		}
		
		taskEmpService.delByTaskId(vo.getUuid());
		//加入主要人员信息，加入协作人员信息
		if(!StringUtils.isEmpty(vo.getEmpNo())){
			PmTaskEmpVo taskEmpVo = new PmTaskEmpVo();
			taskEmpVo.setTaskId(vo.getUuid());
			taskEmpVo.setEmpNo(vo.getEmpNo());
			taskEmpVo.setPrjId(vo.getPrjId());
			taskEmpVo.setRoleType(1);
			taskEmpService.add(taskEmpVo);
			
			if(!StringUtils.isEmpty(vo.getEmpNos())){
				String[] attr = vo.getEmpNos().split(",");
				for (String str : attr) {
					taskEmpVo = new PmTaskEmpVo();
					taskEmpVo.setTaskId(vo.getUuid());
					taskEmpVo.setPrjId(vo.getPrjId());
					taskEmpVo.setEmpNo(str);
					taskEmpVo.setRoleType(0);
					taskEmpService.add(taskEmpVo);
				}
			}
		};
		
		if(!StringUtils.isEmpty(vo.getEmpNos())){
			String[] attr = vo.getEmpNos().split(",");
			for (String str : attr) {
				AuapTEmpVo empVo = empService.findByEmpNo(str);
				if(empVo != null){
					vo.setEmpName(empVo.getEmpName());
					msgService.installMsgVo(vo, MessageConstant.TASK_UPDATE);// update Vo 
				}
			}
		}
		
		return vo;
	}
	
	/**
	 * 任务查询
	 * @param stepId
	 * @return
	 */
	@RequestMapping(value ="list", method = RequestMethod.POST)
	@ResponseBody
	public List<TaskVo> list(String stepId) {
		List<TaskVo> list = taskService.queryValidList(stepId);
		return list;
	}
	
	/**
	 * 任务删除
	 * @param uuid
	 * @return
	 */
	@RequestMapping(value ="delete", method = RequestMethod.POST)
	@ResponseBody
	public String delete(@RequestBody String uuid){
		taskService.deleteById(uuid);
		return JsonSuccess.factory("删除成功");
	}
	

	/**
	 * 主键查询
	 * @param id
	 * @throws AppException 
	 */
	@RequestMapping(value ="getById", method = RequestMethod.POST)
	@ResponseBody
	public TaskVo getById(@RequestBody String id) throws AppException{
		TaskVo vo = taskService.getById(id);
		if(vo == null){
			throw new AppException("任务不存在，可能已经被删除，请刷新！");
		}
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("taskId", id);
		params.put("roleType", 0);
		List<PmTaskEmpVo> list = taskEmpService.queryForList(params);
		List<String> empNoList = new ArrayList<String>();
		for (PmTaskEmpVo pmTaskEmpVo : list) {
			empNoList.add(pmTaskEmpVo.getEmpNo());
		}
		vo.setEmpNosList(empNoList);
		return vo;
	}
	/**
	 * 查询人员任务
	 * @param id
	 * @throws AppException 
	 */
	@RequestMapping(value ="findByEmpNo", method = RequestMethod.POST)
	@ResponseBody
	public List<TaskVo> findByEmpNo(@RequestBody String empNo) throws AppException{
		List<TaskVo> list = taskService.findByEmpNo(empNo);
		return list;
	}
	/**
	 * 查询某个时间段的任务
	 * @param start 开始时间
	 * @param end 结束时间
	 * @return
	 */
	@RequestMapping(value ="queryStartEndTime", method = RequestMethod.GET)
	@ResponseBody
	public List<TaskCalendarBo> queryStartEndTime(Long start, Long end, String empNo){
		Date startDate = DateUtils.longToDate(start);
		Date endDate = DateUtils.longToDate(end);
		
		if (StringUtils.isEmpty(empNo)) {
			empNo = SessionUserUtil.getCurrentUser().getUserNo();
		}
		
		List<TaskCalendarBo> indexBos = taskService.queryTaskCalendar(startDate, endDate, empNo);
		
		return indexBos;
	}
	

	/**
	 * 确认任务完成
	 *  @param taskId
	 * @throws AppException 
	 */
	@RequestMapping(value ="auditComplete", method = RequestMethod.GET)
	@ResponseBody
	public String auditComplete(String taskId,String comment,String prjId) throws AppException{
		
		String empNo =  SessionUserUtil.getCurrentUser().getUserNo();
		
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("busitableKey", taskId);
		params.put("submitType", PmConstant.TASK);
		params.put("targetEmpNo", empNo);
		params.put("prjId", prjId);
		
		AsmgSubmitInfoVo submitInfoVo = new AsmgSubmitInfoVo();
		List<AsmgSubmitInfoVo> list = submitService.queryForList(params);
		if(Collections3.isNotEmpty(list)){
			submitInfoVo = list.get(0);
		}
		params.clear();
		params.put("uuid", submitInfoVo.getUuid());
		params.put("status", PmConstant.SUCCESS);
		params.put("comment", comment);
		super.setUpdateOperInfo(params);
		
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("uuid", taskId);
		map.put("status", PmConstant.TASK_STATUS_FLISH);
		super.setUpdateOperInfo(map);
			
		taskService.changeTaskStatus(map,params,MessageConstant.TASK_AUDIT_SUCCESS);
		
			
		return JsonSuccess.factory("设置成功");
	}
	
	/**
	 * 成员提交任务
	 *  @param taskId
	 * @throws AppException 
	 */
	@RequestMapping(value ="complete", method = RequestMethod.GET)
	@ResponseBody
	public String complete(String taskId,String comment,String prjId) throws AppException{
		
			AsmgSubmitInfoVo submitInfoVo = new AsmgSubmitInfoVo();
			submitInfoVo.setBusitableKey(taskId);
			submitInfoVo.setComment(comment);
			submitInfoVo.setSubmitType(PmConstant.TASK);
			submitInfoVo.setStatus(PmConstant.SUBMIT);
			
			submitInfoVo.setPrjId(prjId);
			List<TeamVo> teamList = teamService.findByPrjIdAndRoleNo(prjId, PmConstant.PRJ_ROLE_PRINCIPAL);
			if(Collections3.isNotEmpty(teamList)){
				submitInfoVo.setTargetEmpNo(teamList.get(0).getEmpNo());
			}else{
				throw new AppException("无项目负责人，任务不能提交！");
			}
			taskService.changeTaskStatus(taskId, PmConstant.TASK_STATUS_COMMIT,combineSubmitInfo(submitInfoVo));
			
		return JsonSuccess.factory("设置成功");
	}
	
	/**
	 * 项目经理驳回任务
	 *  @param taskId
	 * @throws AppException 
	 */
	@RequestMapping(value ="rejectTask", method = RequestMethod.GET)
	@ResponseBody
	public String rejectTask(String taskId,String comment,String prjId) throws AppException{
		
		String empNo =  SessionUserUtil.getCurrentUser().getUserNo();
		
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("busitableKey", taskId);
		params.put("submitType", PmConstant.TASK);
		params.put("targetEmpNo", empNo);
		params.put("prjId", prjId);
		
		AsmgSubmitInfoVo submitInfoVo = new AsmgSubmitInfoVo();
		List<AsmgSubmitInfoVo> list = submitService.queryForList(params);
		if(Collections3.isNotEmpty(list)){
			submitInfoVo = list.get(0);
		}
		params.clear();
		params.put("uuid", submitInfoVo.getUuid());
		params.put("status", PmConstant.FAILURE);
		params.put("comment", comment);
		super.setUpdateOperInfo(params);
		
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("uuid", taskId);
		map.put("status", PmConstant.TASK_STATUS_BEBACK);
		map.put("endDate", null);
		super.setUpdateOperInfo(map);
			
		taskService.changeTaskStatus(map,params,MessageConstant.TASK_TOBACK);
			
		return JsonSuccess.factory("设置成功");
	}
	/**
	 * 根据任务状态查询信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value="selectStatus",method=RequestMethod.GET)
	@ResponseBody
	public List<TaskVo> selectStatus(String struts, String empNo, String roleNo){
		
		if (StringUtils.isEmpty(empNo) || StringUtils.isEmpty(roleNo)) {
			 empNo =  SessionUserUtil.getCurrentUser().getUserNo();
			 roleNo =  SessionUserUtil.getCurrentUser().getRoleNo();
		} 
		
		
		List<TaskVo> taskList = taskService.queryListStatus(empNo,struts);
		if(PmConstant.TASK_STATUS_COMMIT.equals(struts)){
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("targetEmpNo", empNo);
			map.put("submitType", PmConstant.TASK);
			map.put("status", PmConstant.SUBMIT);
			List<AsmgSubmitInfoVo> list = submitService.queryForList(map);
			if(Collections3.isNotEmpty(list)){
				for (AsmgSubmitInfoVo asmgSubmitInfoVo : list) {
					taskList.add(taskService.getById(asmgSubmitInfoVo.getBusitableKey()));
				}
			}
		}
		
		for (TaskVo taskVo : taskList) {
			if(taskVo.getEndDate()==null){
				taskVo.setEndDate(taskVo.getPlanEndDate());
			}
		}
		return taskList;
	}
	
	/**
	 * 格局状态查询文件审核信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value="selectAuditTask",method=RequestMethod.GET)
	@ResponseBody
	public List<FileVo> selectAuditTask(String struts, String empNo, String roleNo){
		
		if (StringUtils.isEmpty(empNo) || StringUtils.isEmpty(roleNo)) {
			 empNo =  SessionUserUtil.getCurrentUser().getUserNo();
			 roleNo =  SessionUserUtil.getCurrentUser().getRoleNo();
		}
		
		
		List<FileVo> fileList = new ArrayList<FileVo>();
		FileVo fileVo = null;
		if("ProjectManager".equals(roleNo)||(roleNo.indexOf("DE")>0)||"studioManager".equals(roleNo)){
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("targetEmpNo", empNo);
			map.put("status", struts);
			map.put("submitType", PmConstant.FRUIT);
			List<AsmgSubmitInfoVo> list = submitService.queryForList(map);
			if(Collections3.isNotEmpty(list)){
				for (AsmgSubmitInfoVo asmgSubmitInfoVo : list) {
					fileVo = fileService.getById(asmgSubmitInfoVo.getBusitableKey());
					fileVo.setCreateDt(asmgSubmitInfoVo.getCreateDt());
					fileVo.setUpdateDt(asmgSubmitInfoVo.getUpdateDt());
					fileList.add(fileVo);
				}
			}
			map.put("submitType", PmConstant.PROJECT);
			List<AsmgSubmitInfoVo> prolist = submitService.queryForList(map);
			if(Collections3.isNotEmpty(prolist)){
				for (AsmgSubmitInfoVo asmgSubmitInfoVo : prolist) {
					FileVo fileVo2 = new FileVo();
					ProjectVo projectVo = projectService.getById(asmgSubmitInfoVo.getBusitableKey());
					if(projectVo != null){
						fileVo2.setFileName(projectVo.getPrjName());
						fileVo2.setProjectId(asmgSubmitInfoVo.getBusitableKey());
						fileVo2.setCreateDt(asmgSubmitInfoVo.getCreateDt());
						fileVo2.setUpdateDt(asmgSubmitInfoVo.getUpdateDt());
						fileList.add(fileVo2);
					}
				}
			}
			
			
			List<FileVo> reviewList = new ArrayList<FileVo>();
			int i = 0;
			for (FileVo  vo : fileList) {
				if (i >= 10) {
					break;
				}
				reviewList.add(vo);
				++i;
			}
			return reviewList;
		}
		return new ArrayList<FileVo>();
		
	}
	
	/**
	 * 通过stepId查询相关的附件  和 文价夹信息  但是要去掉表pmStepDocCfg表中存在的数据
	 * @param stepId
	 * @return
	 */
	@RequestMapping(value="selectTaskId",method=RequestMethod.GET)
	@ResponseBody
	public List<TaskFileBo> selectTaskId(String stepId){	
		
		List<TaskFileBo> fileBos = Lists.newArrayList();
		fileBos = taskService.selectStepId(stepId);	
		
		//查询阶段成果
		List<PrjFruitFileBo> PrjFruitFileList = selectFruitFile(stepId);
		for (PrjFruitFileBo prjFruitFileBo : PrjFruitFileList) {
			TaskFileBo taskBo = new TaskFileBo();
			taskBo.setFolderName(prjFruitFileBo.getShowName());
			taskBo.setUuid(prjFruitFileBo.getUuid());
			taskBo.setParentId(prjFruitFileBo.getParentId());
			taskBo.setFolderType(prjFruitFileBo.getFolderType());
			fileBos.add(taskBo);
		}
		return fileBos;
	}
	

	/**
	 * 查询阶段成果
	 * @param stepId
	 * @return
	 */
	public List<PrjFruitFileBo> selectFruitFile(String stepId) {
		List<PrjFruitFileBo> list =  new ArrayList<PrjFruitFileBo>();
		PrjFruitFileBo  bo =  new PrjFruitFileBo();
		StepVo stepVo = stepService.getById(stepId);
		bo = new PrjFruitFileBo();
		bo.setUuid(stepVo.getUuid());
		bo.setShowName(stepVo.getStepName());
		bo.setParentId(stepVo.getPrjId());
		bo.setFolderType("40010001");
		list.add(bo);
		List<FileVo> fileList = fileService.queryFileByBusiId(stepVo.getUuid());
		for (FileVo fileVo : fileList) {
			bo = new PrjFruitFileBo();
			bo.setUuid(fileVo.getUuid());
			bo.setShowName(fileVo.getFileName());
			bo.setParentId(stepVo.getUuid());
			bo.setStatus(queryStatusByKey(fileVo.getUuid()));
			bo.setFolderType("40010002");
			list.add(bo);
		}
		return list;
	}
	
	private String queryStatusByKey(String busitableKey){
		String empNo =  SessionUserUtil.getCurrentUser().getUserNo();
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("busitableKey", busitableKey);
		map.put("targetEmpNo", empNo);
		List<AsmgSubmitInfoVo> list = submitInfoService.queryForList(map);
		if(Collections3.isEmpty(list)){
			return "";
		}else{
			return list.get(0).getStatus();
		}
	}
	
	
	/**
	 * 组装提交信息对象
	 * @param submitInfoVo
	 * @return
	 */
	public AsmgSubmitInfoVo combineSubmitInfo(AsmgSubmitInfoVo submitInfoVo){
		
		SessionUserHolder user = SessionUserUtil.getCurrentUser();
		submitInfoVo.setSubmitEmpNo(user.getUserNo());
		super.setInsertOperInfo(submitInfoVo);		
		return submitInfoVo;
	}
	

}
